/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/house-robber-iii
   @Language: C++
   @Datetime: 19-04-02 13:37
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	pair<int,int> postorder(TreeNode *root){
		if(root==NULL) return {0,0};
		const auto &left=postorder(root->left);
		const auto &right=postorder(root->right);
		return {root->val+left.second+right.second,
			max(left.first,left.second)+max(right.first,right.second)};
	}
public:
	/**
	 * @param root: The root of binary tree.
	 * @return: The maximum amount of money you can rob tonight
	 */
	int houseRobber3(TreeNode * root) {
		// write your code here
		const auto &p=postorder(root);
		return max(p.first,p.second);
	}
};
